﻿/*

The MIT License

Copyright (c) 2010 Cartesian Analytics, Inc. 

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.

*/

using System;
using System.Collections.Generic;
using System.IO;
using System.Text.RegularExpressions;
using Pipra.Math.Geometry;

namespace Pipra.Gis.Test
{
    public class GeoTransGoldDataReader : IDisposable
    {

        private readonly bool _ownStream;
        private TextReader _reader;
        private string _curLine;
        private bool _inHeader;
        private Dictionary<string, string> _header;

        private static readonly Regex headerLineRegex = new Regex(@"^\s*([^#]+)\s*[:]\s*([^#]+)\s*(?:[#].*)?$", RegexOptions.Compiled);
        private static readonly Regex point2Regex = new Regex(@"^\s*([^#]+)\s*[:,]\s*([^#]+)\s*(?:[#].*)?$", RegexOptions.Compiled);
        private static readonly Regex point3Regex = new Regex(@"^\s*([^#]+)\s*[,]\s*([^#]+)\s*[,]\s*([^#]+)\s*(?:[#].*)?$", RegexOptions.Compiled);
        private static readonly Regex commentRegex = new Regex(@"^\s*[#].*", RegexOptions.Compiled);


        public GeoTransGoldDataReader(TextReader reader)
        {
            if (null == reader)
            {
                throw new ArgumentNullException("reader");
            }
            _reader = reader;
            _inHeader = true;
            _curLine = null;
            _ownStream = false;
        }

        public bool Read()
        {
            if (_inHeader)
            {
                _header = new Dictionary<string, string>(StringComparer.InvariantCultureIgnoreCase);
                do
                {
                    _curLine = _reader.ReadLine();
                    if (null == _curLine)
                    {
                        return false;
                    }
                    _curLine = _curLine.Trim();
                    Match m = headerLineRegex.Match(_curLine);
                    if (m.Groups.Count >= 3)
                    {
                        _header[m.Groups[1].Value.Trim()] = m.Groups[2].Value.Trim();
                    }
                } while (!"END OF HEADER".Equals(_curLine.Trim()));
                _curLine = null;
                _inHeader = false;
                return true;
            }
            else
            {
                do
                {
                    _curLine = _reader.ReadLine();
                    if (null == _curLine)
                    {
                        return false;
                    }
                } while (String.IsNullOrEmpty(_curLine) || commentRegex.IsMatch(_curLine));
                return true;
            }
        }

        public string this[string key]
        {
            get
            {
                string value;
                return (
                    (_header.TryGetValue(key, out value))
                    ? value
                    : null
                );
            }
        }

        public Point2 CurrentPoint2D()
        {
            if (null != _curLine)
            {
                Match m = point2Regex.Match(_curLine);
                if (m.Groups.Count >= 3)
                {
                    return new Point2(
                        Double.Parse(m.Groups[1].Value.Trim()),
                        Double.Parse(m.Groups[2].Value.Trim())
                    );
                }
            }
            return new Point2(Double.NaN, Double.NaN);
        }

        public void Dispose()
        {
            if (null != _reader && _ownStream)
            {
                _reader.Dispose();
                _reader = null;
            }
        }


        public LatLon CurrentLatLon()
        {
            if (null != _curLine)
            {
                Match m = point2Regex.Match(_curLine);
                if (m.Groups.Count >= 3)
                {
                    return new LatLon(
                        Double.Parse(m.Groups[1].Value.Trim()),
                        Double.Parse(m.Groups[2].Value.Trim())
                    );
                }
            }
            return new LatLon(Double.NaN, Double.NaN);
        }

        public LatLon CurrentLatLonRadians()
        {
            LatLon coord = CurrentLatLon();
            return new LatLon(coord.Lat / 180.0 * System.Math.PI, coord.Lon / 180.0 * System.Math.PI);
        }

    }
}
